<template>
  <div p-5>
    <DynamicTable
      :data-request="loadTableData"
      :columns="columns"
      bordered
      :scroll="{
        y: 'calc(100vh - 330px)',
      }"
    >
      <template #toolbar>
        <a-space>
          <a-upload
            :action="`${actionUrl}/manage/placeInfo/importPlaceInfo`"
            accept=".xls"
            :maxCount="1"
            :headers="uploadHeader"
            :showUploadList="false"
            @change="handleUpload"
            :before-upload="beforeUpload"
          >
            <a-button type="primary"> 导入 </a-button>
          </a-upload>

          <a-button type="primary" @click="handleDown"> 下载模板 </a-button>
        </a-space>
      </template>
    </DynamicTable>
  </div>
</template>
<script setup lang="ts">
  import { onMounted, ref } from 'vue';
  import router from '@/router';
  import { message } from 'ant-design-vue';
  import { Storage } from '@/utils/Storage';
  import { getSitePageList, downTemplate } from '@/api/site';
  import { useTable } from '@/components/core/dynamic-table';
  import { baseColumns, type TableColumnItem } from './columns';
  import { ACCESS_TOKEN_KEY } from '@/enums/cacheEnum';
  import { getSelectAreaList } from '@/api/administrativePenalty/case-management';

  defineOptions({
    name: 'SiteManagement',
  });

  const [DynamicTable, dynamicTableInstance] = useTable();

  //区域相关
  const countyOptions = ref([] as any);
  const townOptions = ref([] as any);

  const areaFieldNames = {
    label: 'name',
    value: 'id',
  };

  /**
   * 表格数据
   */

  const loadTableData = async (params): Promise<API.TableListResult> => {
    const data = await getSitePageList(params);

    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          list: data,
          ...params,
        });
      }, 500);
    });
  };

  /**
   * @description 详情页面
   */

  const columns: TableColumnItem[] = [
    ...baseColumns,
    {
      title: '所在地区',
      dataIndex: 'countyCode',
      hideInTable: true,
      formItemProps: {
        component: 'Select',
        labelWidth: 80,
        colProps: {
          style: 'width: 240px',
        },
        componentProps: ({ formModel, formInstance }) => {
          return {
            placeholder: '请选择区域',
            options: countyOptions.value,
            fieldNames: areaFieldNames,
            autocomplete: 'off',
            disabledLabelWidth: true,
            onChange: (e: any) => {
              countyOptions.value.map((item) => {
                if (item.id == e) {
                  townOptions.value = item.children;
                }
              });
              formModel.townCode = undefined;
              const { updateSchema } = formInstance;
              updateSchema({
                field: 'townCode',
                componentProps: {
                  options: townOptions.value,
                },
              });
            },
          };
        },
      },
    },
    {
      title: '',
      dataIndex: 'townCode',
      hideInTable: true,
      formItemProps: {
        component: 'Select',
        labelWidth: 10,
        colProps: {
          style: 'width: 175px',
        },
        componentProps: () => {
          return {
            placeholder: '请选择街道',
            options: [],
            fieldNames: areaFieldNames,
            autocomplete: 'off',
            disabledLabelWidth: true,
          };
        },
      },
    },
    {
      title: '操作',
      width: 40,
      dataIndex: 'ACTION',
      align: 'center',
      actions: ({ record }) => [
        {
          label: '详情',
          onClick: () =>
            router.push({
              path: '/site/siteInfo',
              query: { id: record.id },
            }),
        },
      ],
    },
  ];

  //上传
  const actionUrl = ref(import.meta.env.VITE_BASE_API);
  const uploadHeader = {
    'API-User-Token': Storage.get(ACCESS_TOKEN_KEY),
  };

  const handleUpload = (info) => {
    if (info.file.status === 'done') {
      if (info.file?.response.code == 0) {
        message.success(`${info.file.name}导入成功`);
        dynamicTableInstance?.reload();
      } else {
        message.error(`${info.file.name}${info.file?.response.message}`);
      }
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name}导入失败`);
    }
  };

  const beforeUpload = (file, fileList) => {
    let fileType = fileList[0].name.replace(/.+\./, '');
    if (fileType !== 'xls') {
      message.error(`只支持上传xls类型`);
    } else {
      return;
    }
  };

  const downFile = (url, name) => {
    var fileUrl = url; // 文件的URL
    var fileName = name; // 新的文件名

    var xhr = new XMLHttpRequest();
    xhr.open('GET', fileUrl, true);
    xhr.responseType = 'blob';

    xhr.onload = function () {
      if (xhr.status === 200) {
        var blob = xhr.response;
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;
        link.click();
      }
    };

    xhr.send();
  };

  const handleDown = async () => {
    let checkItem = '场所模板';
    downFile(
      `${import.meta.env.VITE_BASE_API}/manage/upload/downloadFile?fileUrl=folder1/placeInfo.xls`,
      `${checkItem}.xls`,
    );
  };

  onMounted(async () => {
    const res_area = await getSelectAreaList();
    if (res_area.code === 0) {
      countyOptions.value = res_area.data[0].children;
    }
  });
</script>
<style scoped lang="less"></style>
